(function( $ ) {
    $.fn.SPDynamicQuickLaunch = function(options) {
        var options = $.extend( {
            'append'  : false
        }, options);

        return this.each(function() {
            var $this = $(this);
            var nodes = Node.ParseJsonNodes(options.nodes);

            for(var i=0;i<nodes.length;i++)
            {
                var node = nodes[i];
                node.AttachToMenu($this, options.append);
            }
        });
    };
})( jQuery );



function Node(url, label, selected) {
    this.Url = url;
    this.Label = label;
    this.Selected = selected;
    //this.Template = "<li class='static{Selected}'><a class='static menu-item' href='{Url}'><span class='additional-background'><span class='menu-item-text'>{Label}</span></span></a></li>";

    this.Children = new Array();
}

Node.ParseJsonNodes = function(jNodes)
{
    var output = new Array();
    for(var i=0;i<jNodes.length;i++)
    {
        var jNode = jNodes[i];
        var node = new Node(jNode.url,jNode.label,jNode.selected);
        if (jNode.children)
        {
            node.Children = Node.ParseJsonNodes(jNode.children);
        }
        output.push(node);
    }
    return output;
}

Node.Template = "<li class='static{Selected}'><a class='static menu-item' href='{Url}'><span class='additional-background'><span class='menu-item-text'>{Label}</span></span></a></li>";

Node.prototype.AddChild = function (node) {
    this.Children.push(node);
};

Node.prototype.GetHtml = function () {
    var output = Node.Template.replace("{Url}", this.Url).replace("{Label}", this.Label);
    if (this.Selected) {
        output = output.replace('{Selected}', ' selected');
    } else {
        output = output.replace('{Selected}', '');
    }
    return output;
};
Node.prototype.ProcessChilds = function (parentNode) {
    if (this.Children.length > 0) {
        var subList = $("<ul />");
        parentNode.append(subList);
        for (var i = 0; i < this.Children.length; i++) {
            var childNode = this.Children[i];
            var nodeItem = $(childNode.GetHtml());
            subList.append(nodeItem);
            childNode.ProcessChilds(nodeItem);
        }
    }
};

Node.prototype.AttachToMenu = function (menu, append) {
    var nodeItem = $(this.GetHtml());
    if (append)
    {
        menu.append(nodeItem);
    }
    else
    {
        menu.prepend(nodeItem);
    }
    this.ProcessChilds(nodeItem);
};



